package com.youyi.yyscreencutlibrary.Track;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;

import com.lmiot.xyclick.Util.LkxLog;

import org.greenrobot.eventbus.EventBus;

public class TrackScreenService extends Service {
    public IBinder onBind(Intent intent) {
        return null;
    }

    public int onStartCommand(Intent intent, int i, int i2) {
        startForegroundService();
        EventBus.getDefault().post(new StartTrackBean(true));
        return START_STICKY;
    }

    private void createNotificationChannel() {
        PendingIntent pendingIntent;
        Notification.Builder builder = new Notification.Builder(getApplicationContext());
        Intent intent = new Intent("com.youyi.yyscreencutlibrary.Track.TrackScreenService");
        if (Build.VERSION.SDK_INT >= 31) {
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 201326592);
        } else {
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 1073741824);
        }
        builder.setContentIntent(pendingIntent).setContentText("正在录屏").setWhen(System.currentTimeMillis());
        if (Build.VERSION.SDK_INT >= 26) {
            builder.setChannelId("notification_id");
        }
        if (Build.VERSION.SDK_INT >= 26) {
            ((NotificationManager) getSystemService("notification")).createNotificationChannel(new NotificationChannel("notification_id", "notification_name", 2));
        }
        Notification build = builder.build();
        build.defaults = 1;
        startForeground(110, build);
    }

    private void startForegroundService() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        String channelId = "notification_id";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "notification_name", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }
        Notification notification = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            notification = new Notification.Builder(this, channelId)
                    .setContentTitle("Media Projection Active")
                    .setContentText("Your screen is being recorded.")
                    .setOngoing(true)
                    .build();
        }

        startForeground(1, notification);
    }

    public void onDestroy() {
        LkxLog.d("关闭前台服务");
        super.onDestroy();
        stopForeground(true);
    }
}
